﻿ #include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    // 菜单的建立
    m_menu = new QMenu(this);
    m_action1 = new QAction(m_menu);
    m_action2 = new QAction(m_menu);
    m_action1->setText("Show Window");
    m_action2->setText("Show Message");
    m_menu->addAction(m_action1);
    m_menu->addAction(m_action2);
    connect(m_action1, &QAction::triggered, this, &MainWindow::showWindow);
    connect(m_action2, &QAction::triggered, this, &MainWindow::showMessage);
    // 托盘的建立
    m_systemTray = new QSystemTrayIcon(this);
    m_systemTray->setContextMenu(m_menu);
    m_systemTray->setIcon(QIcon("D:\\CBox\\DevelopCodes\\dmyNoteBook\\dmyNoteBook\\images\\ico.png"));
    m_systemTray->setToolTip("SystemTray Program");
    m_systemTray->show();
    connect(m_systemTray, &QSystemTrayIcon::activated, this, &MainWindow::activeTray);//点击托盘，执行相应的动作
    connect(m_systemTray, &QSystemTrayIcon::messageClicked, this, &MainWindow::showWindow);//点击消息框，显示主窗口
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::changeEvent(QEvent *event)
{
    if(event->type() == QEvent::WindowStateChange)
    {
        if(windowState() & Qt::WindowMinimized)
        {
            hide();
        }
    }
    QWidget::changeEvent(event);
}

void MainWindow::activeTray(QSystemTrayIcon::ActivationReason reason)
{
    qDebug() << "activeTray:" << reason;
    switch (reason)
    {
    case QSystemTrayIcon::Context:
        showMenu();
        break;
        //    case QSystemTrayIcon::DoubleClick:
        //        showMessage();
        //        break;
    case QSystemTrayIcon::Trigger:
        showWindow();
        break;
    }
}

void MainWindow::showWindow()
{
    Qt::WindowStates wins;
    if (windowState() & Qt::WindowMaximized)
    {
        wins = Qt::WindowMaximized;
    }
    setWindowState(Qt::WindowActive | wins);
    this->show();
}

void MainWindow::showMessage()
{
    m_systemTray->showMessage("Information",//消息窗口标题
                              "There is a new message!",//消息内容
                              QSystemTrayIcon::MessageIcon::Information,//消息窗口图标
                              5000);//消息窗口显示时长
}

void MainWindow::showMenu()
{
    m_menu->show();
}
